<template>
  <div class="product-list-container">
    <!-- 搜索表单 -->
    <el-form :inline="true">
      <div class="left">
        <el-form-item style="margin-right: 20px">
          <el-select
            @change="searchDepartment"
            v-model="department"
            style="width: 220px"
            placeholder="选择部门进行筛选"
          >
            <el-option
              v-for="item in Department"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-radio-group @change="searchLevel" v-model="messageLevel">
            <el-radio label="一般" value="一般"></el-radio>
            <el-radio label="重要" value="重要"></el-radio>
            <el-radio label="必要" value="必要"></el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="right">
        <el-form-item>
          <el-button type="primary" size="default" plain @click="allMessage">全部公告</el-button>
          <el-button type="primary" size="default" @click="openPublishDialog">发布公告</el-button>
        </el-form-item>
      </div>
    </el-form>
    <!-- 主体表格 -->
    <div class="table">
      <el-table :border="true" :data="noticeList">
        <el-table-column type="index" width="55"></el-table-column>
        <el-table-column
          label="公告主题"
          align="center"
          type="default"
          prop="message_title"
          min-width="260"
        />
        <el-table-column
          min-width="90"
          label="类别"
          align="center"
          type="default"
          prop="message_category"
        />
        <el-table-column
          label="发布部门"
          align="center"
          type="default"
          prop="message_publish_department"
          min-width="90"
        />
        <el-table-column
          min-width="90"
          label="发布人"
          align="center"
          type="default"
          prop="message_publish_name"
        />
        <el-table-column
          label="接收对象"
          align="center"
          type="default"
          prop="message_receipt_object"
          min-width="90"
        />
        <el-table-column
          label="公告等级"
          align="center"
          type="default"
          prop="message_level"
          min-width="100"
        />
        <el-table-column label="发布时间" align="center" type="default" min-width="170"
          ><template v-slot="{ row }">
            {{ formaDate(row.message_create_time) }}
          </template></el-table-column
        >
        <el-table-column
          label="最新编辑时间"
          align="center"
          type="default"
          prop="product_audit_time"
          min-width="170"
        >
          <template v-slot="{ row }">
            {{ row.message_update_time ? formaDate(row.message_update_time) : '未修改' }}
          </template>
        </el-table-column>
        <el-table-column
          label="阅读人数"
          align="center"
          type="default"
          prop="message_click_number"
          min-width="90"
        />
        <el-table-column label="操作" width="160" align="center">
          <template v-slot="{ row }">
            <el-button @click="editMessage(row)" type="success" size="default">编辑</el-button>
            <el-popconfirm
              :title="`你确定要将此公告放入回收站吗`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="toRecycli(row)"
              width="250px"
            >
              <template #reference>
                <el-button type="danger" size="default">删除</el-button>
              </template>
            </el-popconfirm>
          </template></el-table-column
        >
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          class="pagination"
          v-model:current-page="page"
          :page-size="10"
          layout="prev, pager, next, jumper,total"
          :total="total"
        />
      </div>
    </div>
  </div>
  <el-dialog
    @close="close"
    v-model="messageDialog"
    :title="publish ? '发布消息' : '编辑信息'"
    width="45%"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      style="max-width: 600px"
      :rules="rules"
      :model="publishMessage"
    >
      <el-form-item prop="message_title" label="主题">
        <el-input v-model="publishMessage.message_title"></el-input>
      </el-form-item>
      <el-form-item prop="message_publish_department" label="发布部门">
        <el-select :disabled="!publish" v-model="publishMessage.message_publish_department">
          <el-option v-for="item in Department" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="message_publish_name" label="发布人">
        <el-input v-model="publishMessage.message_publish_name" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item prop="message_receipt_object" label="接收部门">
        <el-select v-model="publishMessage.message_receipt_object">
          <el-option label="全体对象" value="全体对象"></el-option>
          <el-option v-for="item in Department" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="message_level" label="公告等级">
        <el-select v-model="publishMessage.message_level">
          <el-option label="一般" value="一般"></el-option>
          <el-option label="重要" value="重要"></el-option>
          <el-option label="必要" value="必要"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="message_content" label="内容">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="publishMessage.message_content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="submit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import moment from 'moment'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onMounted, reactive, ref, watch, shallowRef, onBeforeUnmount } from 'vue'
import {
  editMessageAPI,
  firstDeleteAPI,
  getMessageListAPI,
  publishMessageAPI,
  searchMessageAPI,
  searchMessageByDepartmentAPI,
  searchMessageByLevelAPI
} from '@/api/message'
import { useUserStore } from '@/stores/user'
import { getDepartmentAPI } from '@/api/userAdmin'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ElMessage, type FormRules } from 'element-plus'
import { tracking } from '@/utils/operation'
import { changUserReadListAPI, DeleteUserReadListIdAPI } from '@/api/depMsg'
import { useMessageStore } from '@/stores/message'

const MsgStore = useMessageStore()
const userStore = useUserStore()
const activeName = defineProps(['activeName'])
/** 处理日期 */
const formaDate = (date: string) => {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

/** 获取部门列表 */
const Department = ref<string[]>([])
const getDepartment = async () => {
  const res = await getDepartmentAPI()
  Department.value = JSON.parse(res.data!)
}

/** 存储选择的部门 */
const department = ref<string>('')
/** 存储选择的等级 */
const messageLevel = ref<string>('')
/** 选择部门筛选 */
const searchDepartment = async () => {
  if (messageLevel.value) {
    const res = await searchMessageAPI(page.value, department.value, messageLevel.value)
    noticeList.value = res.data!
    total.value = res.total!
  } else {
    const res = await searchMessageByDepartmentAPI(page.value, department.value)
    noticeList.value = res.data!
    total.value = res.total!
  }
}
/** 选择等级筛选 */
const searchLevel = async () => {
  if (department.value && department.value !== '全部') {
    const res = await searchMessageAPI(page.value, department.value, messageLevel.value)
    noticeList.value = res.data!
    total.value = res.total!
  } else {
    const res = await searchMessageByLevelAPI(page.value, messageLevel.value)
    noticeList.value = res.data!
    total.value = res.total!
  }
}
/** 筛选复原 */
const allMessage = () => {
  department.value = '全部'
  messageLevel.value = ''
  getnoticeList()
}

// 分页器数据
const page = ref<number>(1)
const total = ref<number>(20)

/** 公司公告列表 */
const noticeList = ref<Message[]>([])
const getnoticeList = async () => {
  const res = await getMessageListAPI(page.value, '通知公告')
  noticeList.value = res.data!
  total.value = res.total!
}
/**发布/修改弹窗*/
const messageDialog = ref<boolean>(false)
/** 区分发布/修改 */
const publish = ref<boolean>()
const openPublishDialog = () => {
  publishMessage.message_publish_name = userStore.UserInfo?.name!
  messageDialog.value = true
  publish.value = true
}

/** 单个消息数据 */
const publishMessage = reactive<Message>({
  message_title: '',
  message_publish_name: userStore.UserInfo?.name!,
  message_publish_department: '',
  message_receipt_object: '',
  message_level: '',
  message_category: '通知公告',
  message_content: '',
  message_click_number: 0,
  message_delete_time: null,
  message_update_time: null,
  message_create_time: '',
  message_status: 1
})
/** 编辑信息 */
const editMessage = (row: Message) => {
  Object.assign(publishMessage, row)
  publish.value = false
  messageDialog.value = true
}
/** 获取 发布/编辑表单 实例*/
const formRef = ref()
/** 发布/编辑表单校验 */
const rules = reactive<FormRules<Message>>({
  message_title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  message_publish_department: [
    {
      required: true,
      message: '请选择发布部门',
      trigger: 'blur'
    }
  ],
  message_publish_name: [
    {
      required: true,
      message: '请输入发布人姓名',
      trigger: 'blur'
    }
  ],
  message_level: [
    {
      required: true,
      message: '请选择发布等级',
      trigger: 'blur'
    }
  ],
  message_content: [
    {
      required: true,
      message: '请输入发布内容',
      trigger: 'blur'
    }
  ],
  message_receipt_object: [
    {
      required: true,
      message: '请选择接受部门',
      trigger: 'blur'
    }
  ]
})
/** 发布/编辑提交 */
const submit = async () => {
  await formRef.value.validate()
  if (publish.value) {
    // 发布
    const res = await publishMessageAPI(publishMessage)
    ElMessage({ type: 'success', message: '发布成功' })
    /** 修改阅读列表 */
    await changUserReadListAPI(res.data, publishMessage.message_receipt_object)
    MsgStore.getReadList()
    /** 记录操作 */
    tracking('消息', userStore.UserInfo?.name!, publishMessage.message_title!, '中级', `发布`)
  } else {
    // 编辑
    const res = await editMessageAPI(publishMessage)

    // 从旧部门中删除
    await DeleteUserReadListIdAPI(publishMessage.id!, res.data)
    // 添加到新部门
    await changUserReadListAPI(publishMessage.id!, publishMessage.message_receipt_object)

    MsgStore.getReadList()
    ElMessage({ type: 'success', message: '修改成功' })
    /** 记录操作 */
    tracking('消息', userStore.UserInfo?.name!, publishMessage.message_title!, '中级', `编辑`)
  }
  messageDialog.value = false
  getnoticeList()
}
/** 弹窗关闭清空数据 */
const close = () => {
  formRef.value?.resetFields()
  Object.assign(publishMessage, {
    message_title: '',
    message_publish_name: '',
    message_publish_department: '',
    message_receipt_object: '',
    message_level: '',
    message_category: '通知公告',
    message_content: '',
    message_click_number: 0,
    message_delete_time: null,
    message_update_time: null,
    message_create_time: '',
    message_status: 1
  })
}
/** 放入回收站 */
const toRecycli = async (row: Message) => {
  await firstDeleteAPI(row.id!)
  ElMessage({ type: 'success', message: '删除成功' })
  await DeleteUserReadListIdAPI(row.id!, row.message_receipt_object)
  MsgStore.getReadList()
  /** 记录操作 */
  tracking('消息', userStore.UserInfo?.name!, publishMessage.message_title!, '中级', `放入回收站`)
  getnoticeList()
}
//********************** */
const editorRef = shallowRef()

const toolbarConfig: any = {}
const editorConfig = {
  placeholder: '请输入内容...'
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
toolbarConfig.excludeKeys = [
  'blockquote',
  'bgColor',
  'color',
  'group-more-style',
  'fontFamily',
  'bulletedList',
  'numberedList',
  'lineHeight',
  'todo',
  'emotion',
  'insertLink',
  'group-video',
  'insertTable',
  'codeBlock',
  'divider',
  'fullScreen',
  'group-image'

  // 排除菜单组，写菜单组 key 的值即可
]
/******************************* */

watch([page, activeName], () => {
  if (department.value) {
    searchDepartment()
  } else if (messageLevel.value) {
    searchLevel()
  }
  getnoticeList()
})
onMounted(() => {
  getnoticeList()
  getDepartment()
})
</script>

<style scoped lang="scss">
.product-list-container {
  padding: 0 8px;
  .el-form {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      margin: 0;
    }
  }
  .el-table {
    margin-top: 10px;
  }
  .pagination {
    display: flex;
    justify-content: center;
    margin: 15px;
  }
}
</style>
